package com.zqh.apiindeximgquery.redis;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import io.lettuce.core.ReadFrom;
import org.springframework.boot.autoconfigure.data.redis.LettuceClientConfigurationBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.net.UnknownHostException;

/**
 * @Description :
 * @Author :kono淇杭哒、
 * @Create 2021-10-02 16:21
 */
@Configuration
public class RedisConfig{

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        // 将template 泛型设置为 <String, Object>
        RedisTemplate<String, Object> template = new RedisTemplate();
        // 连接工厂，不必修改
        template.setConnectionFactory(redisConnectionFactory);
        /*
         * 序列化设置
         */
        // key、hash的key 采用 String序列化方式
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());
        // value、hash的value 采用 Jackson 序列化方式
        GenericFastJsonRedisSerializer genericFastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
        // 全局开启AutoType，默认就是开启的，不建议使用（暂时没有发现问题，先用着）
        // ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
        // 建议使用这种方式，小范围指定白名单，需要序列化的类，有需求再使用这个
        //ParserConfig.getGlobalInstance().addAccept("com.avatar");
        template.setValueSerializer(genericFastJsonRedisSerializer);
        template.setHashKeySerializer(genericFastJsonRedisSerializer);

        template.afterPropertiesSet();
        return template;
    }

    /**
     * 功能描述:
     * 配置redis读写策略采用REPLICA _PREFERRED：优先从slave（replica）节点读取，所有的slave都不可用才读取master
     *
     * @param
     * @return com.zqh.apiuserlogin.config.RedisConfig
     * @author kono曾淇杭哒！
     * @date 2022/3/23 15:11
     */
    @Bean
    public LettuceClientConfigurationBuilderCustomizer clientConfigurationBuilderCustomizer(){
        return clientConfigurationBuilder -> clientConfigurationBuilder.readFrom(ReadFrom.REPLICA_PREFERRED);
    }
}

